# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2020-11-23 17:22:32
LastEditors: peng2.zhang
LastEditTime: 2022-01-19 18:15:48
'''

import base64
import ujson
from datetime import datetime
from inspect import signature
from ci_conclude.log import logger


class Validator(object):
    def check_json(self, value):
        try:
            json_res = ujson.loads(value)
            return json_res
        except ValueError as e:
                raise e

    def check_datetime(self, value, fmt='%Y-%m-%d %H:%M:%S'):
        try:
            date = datetime.strptime(value, fmt)
            return value
        except ValueError as e:
            raise e

##################################################################################
# 通过装饰器进行参数校验
##################################################################################
def validate(validate_schema):
    def wrapper(func):
        def inner_wrapper(*args, **kwargs):
            logger.info(f"[validate_schema]: {validate_schema}")
            logger.info(f"[args]: {args}")
            logger.info(f"[kwargs]: {kwargs}")
            sig = signature(func)
            param_keys = list(sig.parameters.keys())
            for index, key in enumerate(param_keys):
                if index == 0 and key == "self":
                    _self = args[0]
                else:
                    _self.params.update({
                        key: args[index]
                    })
            validate_result = _self.check_schema(validate_schema(_self))
            schema = validate_result.data
            setattr(_self, "schema", schema)
            return func(*args, **kwargs)
        return inner_wrapper
    return wrapper